<?php

/*
    Cinema controller provides functionallity related to technical cinema information.
    Can be accessed only by admins.
 */

class Controller_Cinema extends Controller_Template {
    private $user_data;
    private $user_id;
    private $language;
    
    public function before() {
        if(!Auth::member(100)) {
            Response::redirect('/');
        }
        
        $this->language = Cookie::get((Auth::check() ? 'user' : 'guest') . '_language', 'lv');
        Config::set("language", $this->language);
        Lang::load('main', null, $this->language, true);
        
        parent::before();
        $this->user_data = Auth::instance();
        $this->user_id = $this->user_data->get_user_id();
        
        $this->template->language = $this->language;
        $this->template->genres = Model_Orm_Genre::find('all');
        $this->template->cinema_info = Model_Orm_Cinema::find('first');
    }
    
    public function action_info() {
        $cinema_info = Model_Orm_Cinema::find('first');
        
        if(Input::method() == "POST") {
            $validation = Model_Orm_Cinema::validate("add");

            if($validation->run()) {
                if(Upload::is_valid()) {
                    
                    //Custom file upload config
                    $upload_config = array(
                        'path' => DOCROOT.'uploads\\cinema\\',
                        'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png'),
                    );     
                    
                    try {
                        Upload::process($upload_config);
                        Upload::save();
                        $uploaded_file = Upload::get_files();

                        //Deletes the old logo as it won't be used.
                        @unlink(DOCROOT.'uploads\cinema\\'.$cinema_info->logo);
                        $cinema_info->logo = $uploaded_file[0]["saved_as"];
                    }
                    catch(Exception $e) {   //File upload failed.
                        Session::set_flash('error', 'Kļūda augšupielādētajā failā !');
                        Response::redirect('/cinema/info');
                    }
                }
                
                $cinema_info->name = $validation->validated('Cinema_Name');
                $cinema_info->address = $validation->validated('Cinema_Address');
                $cinema_info->slogan = $validation->validated('Cinema_Slogan');
                
                $cinema_info->save();
            }
        }
        
        $view_info = View::forge('cinema/info');
        $view_info->set('cinema_info', $cinema_info);
        $this->template->page_content = $view_info;
    }
}
